package com.example.druid.demo_druid.interceptor;

import com.example.druid.demo_druid.config.DatabaseContextHolder;
import com.example.druid.demo_druid.enums.DatabaseType;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;

/**
 * @author 奶茶
 * Created on 2017/11/2.
 */
@Aspect
@Component
public class ApiAspect {

    private Logger logger = Logger.getLogger(ApiAspect.class);

    @Pointcut("@annotation(com.example.druid.demo_druid.interceptor.DataSource)")
    public void dataSource(){}

    /**
     * 请求之前
     */
    @Before("dataSource()")
    public void doBefore(JoinPoint joinPoint) throws UnsupportedEncodingException, ClassNotFoundException {
        String methodName = joinPoint.getSignature().getName();
        Class<?> targetClass = Class.forName(joinPoint.getTarget().getClass().getName());
        for(Method method : targetClass.getMethods()){
            if(methodName.equals(method.getName())){
                Class<?>[] args = method.getParameterTypes();
                if(args.length == joinPoint.getArgs().length){
                    DataSource ds = method.getAnnotation(DataSource.class);
                    DatabaseContextHolder.setDatabaseType(ds.databaseType());
                }
            }
        }
    }
}
